import datetime
import json
import traceback

from django.db import transaction
from django.db.models import Q

from models import *
from Puer.constant import constant
from django.http import HttpResponse
from Puer.publicUtils.public_method import get_location_info, get_page_start_end


# 查看更多活动
def show_more_activities(request):
    try:
        longitude = request.GET.get("longitude")
        latitude = request.GET.get("latitude")
        city = get_location_info(longitude, latitude)
        data = []
        activity_result = Activity.objects.filter(status=constant.ACTIVITY_PROCESSING, city__contains=city)
        for activity in activity_result:
            activity_host_result = Activityhost.objects.filter(activityid=activity.activityid)
            activity_guest_result = Activityguest.objects.filter(activityid=activity.activityid)
            data.append({
                "activity_id": activity.activityid,
                "activity_title": activity.activitytitle,
                "activity_city": activity.city,
                "activity_time": activity.activitytime,
                "activity_content": activity.content,
                "activity_pic": "%s%s" % (constant.FILE_ADDRESS, activity.picture),
                "activity_hosts": ",".join([activity_host.name for activity_host in activity_host_result]),
                "activity_guests": ",".join([activity_guest.name for activity_guest in activity_guest_result])
            })
        return HttpResponse(json.dumps(data))
    except Exception as exc:
        error_msg = "%s" % traceback.format_exc()
        return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)


# 活动详情
def get_activity_detail(request):
    try:
        activity_id = request.GET.get("activityId")
        activity_obj = Activity.objects.get(activityid=activity_id, status=constant.ACTIVITY_PROCESSING)
        activity_host_result = Activityhost.objects.filter(activityid=activity_id)
        activity_guest_result = Activityguest.objects.filter(activityid=activity_id)
        if activity_obj:
            all_host_msg = {}
            for activity_host_info in activity_host_result:
                all_host_msg.update({
                    "host_id": activity_host_info.hostid,
                    "host_name": activity_host_info.name,
                    "host_profile": '%s%s' % (constant.FILE_ADDRESS, activity_host_info.picaddress),
                    "host_introduce": activity_host_info.introduce
                })
            all_guest_msg = []
            for activity_guest_info in activity_guest_result:
                all_guest_msg.append({
                    "guest_id": activity_guest_info.guestid,
                    "guest_name": activity_guest_info.name,
                    "guest_profile": '%s%s' % (constant.FILE_ADDRESS, activity_guest_info.picaddress),
                    "guest_introduce": activity_guest_info.introduce

                })

            data = {
                "activity_id": activity_obj.activityid,
                "activity_pic": '%s%s' % (constant.FILE_ADDRESS, activity_obj.picture),
                "activity_content": activity_obj.content,
                "activity_hosts_msg": all_host_msg,
                "activity_guests_msg": all_guest_msg
            }
        return HttpResponse(json.dumps(data), content_type=constant.CONTENT_TYPE)
    except Exception as exc:
        error_msg = "%s" % traceback.format_exc()
        return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)


# 活动报名
def join_activity(request):
    try:
        get_user_id = request.GET.get('userId')
        get_activity_id = request.GET.get('activityId')
        get_name = request.GET.get('name')
        get_phone = request.GET.get('phone')
        get_address = request.GET.get('address')
        get_job = request.GET.get('job')
        get_area = request.GET.get('area')
        get_age = request.GET.get('age')
        get_gender = request.GET.get('sex')
        get_hobby = request.GET.get('hobby')

        Activitysign.objects.create(
            activityid=int(get_activity_id),
            userid=get_user_id,
            signtime=datetime.datetime.now(),
            profession=get_job,
            age=get_age,
            sex=get_gender,
            name=get_name,
            phone=get_phone,
            area=get_area,
            address=get_address,
            hobby=get_hobby
        )
        return HttpResponse(json.dumps('success'), content_type=constant.CONTENT_TYPE)
    except Exception as exc:
        error_msg = "%s" % traceback.format_exc()
        return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)


# ----------------------------------------PC------------------------------------------------

# 活动新增

def add_activity(request):
    try:
        get_activity_title = request.POST.get('activityTitle')
        get_activity_city = request.POST.get('activityCity')

        # get_activity_no = request.POST.get('activityNo')
        # print(get_activity_no)
        get_activity_time = request.POST.get('activityTime')
        get_activity_content = request.POST.get('activityContent')
        get_activity_pic = request.FILES.get('activityPic')
        get_host_name = request.POST.get('hostName')
        get_host_introduce = request.POST.get('hostIntroduce')
        get_host_pic = request.FILES.get("hostPic")

        # get_guest = request.POST.get('guest')
        # print(get_guest)

        get_guest_name1 = request.POST.get('guestName1', None)
        get_guest_introduce1 = request.POST.get('guestIntroduce1', None)
        get_pic1 = request.FILES.get('guestPic1', None)
        get_guest_name2 = request.POST.get('guestName2', None)
        get_guest_introduce2 = request.POST.get('guestIntroduce2', None)
        get_pic2 = request.FILES.get('guestPic2', None)
        get_guest_name3 = request.POST.get('guestName3', None)
        get_guest_introduce3 = request.POST.get('guestIntroduce3', None)
        get_pic3 = request.FILES.get('guestPic3', None)
        get_guest_name4 = request.POST.get('guestName4', None)
        get_guest_introduce4 = request.POST.get('guestIntroduce4', None)

        get_pic4 = request.FILES.get('guestPic4', None)
        get_guest_name5 = request.POST.get('guestName5', None)
        get_guest_introduce5 = request.POST.get('guestIntroduce5', None)
        get_pic5 = request.FILES.get('guestPic5', None)
        with transaction.atomic():

            activity = Activity()
            activity.activitytitle = get_activity_title
            activity.content = get_activity_content
            activity.activitytime = get_activity_time
            activity.remark = datetime.datetime.now().strftime("%Y%m%d") + '-%03d' % len(
                Activity.objects.filter(status=constant.UNDERWAY))

            activity.city = get_activity_city
            activity.picture = get_activity_pic
            activity.status = constant.UNDERWAY
            activity.save()
            activity_id = activity.activityid

            host = Activityhost()
            host.activityid = activity_id
            host.picaddress = get_host_pic
            host.name = get_host_name
            host.introduce = get_host_introduce
            host.save()
            if get_guest_name1:
                guest = Activityguest()
                guest.activityid = activity_id
                guest.picaddress = get_pic1
                guest.name = get_guest_name1
                guest.introduce = get_guest_introduce1
                guest.save()

            if get_guest_name2:
                guest2 = Activityguest()
                guest2.activityid = activity_id
                guest2.picaddress = get_pic2
                guest2.name = get_guest_name2
                guest2.introduce = get_guest_introduce2
                guest2.save()
            if get_guest_name3:
                guest3 = Activityguest()
                guest3.activityid = activity_id
                guest3.picaddress = get_pic3
                guest3.name = get_guest_name3
                guest3.introduce = get_guest_introduce3
                guest3.save()
            if get_guest_name4:
                guest4 = Activityguest()
                guest4.activityid = activity_id
                guest4.picaddress = get_pic4
                guest4.name = get_guest_name4
                guest4.introduce = get_guest_introduce4
                guest4.save()
            if get_guest_name5:
                guest5 = Activityguest()
                guest5.activityid = activity_id
                guest5.picaddress = get_pic5
                guest5.name = get_guest_name5
                guest5.introduce = get_guest_introduce5
                guest5.save()

            return HttpResponse(json.dumps('success'), content_type=constant.CONTENT_TYPE)


    except:
        error_msg = "%s" % traceback.format_exc()
        return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)


# # 添加主持人
# def add_host(request):
#     try:
#         get_activity_id = int(request.GET.get('activityId'))
#         get_pic = request.FILES.get('pic')
#         get_name = request.GET.get('name')
#         get_introduce = request.GET.get('introduce')
#         if get_activity_id and get_pic and get_name and get_introduce:
#
#             Activityhost.objects.create(
#                 activityid=get_activity_id,
#                 picaddress=get_pic,
#                 name=get_name,
#                 introduce=get_introduce
#             )
#             return HttpResponse(json.dumps('success'), content_type=constant.CONTENT_TYPE)
#         else:
#             return HttpResponse(json.dumps(["failure", 'parameter not enough ']), content_type=constant.CONTENT_TYPE)
#     except:
#         error_msg = "%s" % traceback.format_exc()
#         return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)
#
#
# # 删除活动主持人
# def delete_host(request):
#     try:
#         get_activity_id = int(request.GET.get('activityId'))
#         get_host_id = int(request.GET.get('hostId'))
#         if get_activity_id and get_host_id:
#             Activityhost.objects.filter(activityid=get_activity_id, hostid=get_host_id).delete()
#             return HttpResponse(json.dumps('success'), content_type=constant.CONTENT_TYPE)
#         else:
#             return HttpResponse(json.dumps(["failure", 'parameter not enough ']), content_type=constant.CONTENT_TYPE)
#     except:
#         error_msg = "%s" % traceback.format_exc()
#         return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)
#
#
# # 添加活动嘉宾
# def add_guest(request):
#     try:
#         get_activity_id = int(request.GET.get('activityId'))
#         get_pic = request.FILES.get('pic')
#         get_name = request.GET.get('name')
#         get_introduce = request.GET.get('introduce')
#         if get_activity_id and get_pic and get_name and get_introduce:
#
#             Activityguest.objects.create(
#                 activityid=get_activity_id,
#                 picaddress=get_pic,
#                 name=get_name,
#                 introduce=get_introduce
#             )
#             return HttpResponse(json.dumps('success'), content_type=constant.CONTENT_TYPE)
#         else:
#             return HttpResponse(json.dumps(["failure", 'parameter not enough ']), content_type=constant.CONTENT_TYPE)
#     except:
#         error_msg = "%s" % traceback.format_exc()
#         return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)
#
#
# # 删除活动嘉宾
# def delete_guest(request):
#     try:
#         get_activity_id = int(request.GET.get('activityId'))
#         get_guest_id = int(request.GET.get('guestId'))
#         if get_activity_id and get_guest_id:
#             Activityguest.objects.filter(activityid=get_activity_id, hostid=get_host_id).delete()
#             return HttpResponse(json.dumps('success'), content_type=constant.CONTENT_TYPE)
#         else:
#             return HttpResponse(json.dumps(["failure", 'parameter not enough ']), content_type=constant.CONTENT_TYPE)
#     except:
#         error_msg = "%s" % traceback.format_exc()
#         return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)


# 活动结束
def end_activity(request):
    try:
        get_activity_id = int(request.GET.get('activityId'))
        Activity.objects.filter(activityid=get_activity_id, status=constant.UNDERWAY).update(status=constant.END)
        return HttpResponse(json.dumps('success'), content_type=constant.CONTENT_TYPE)
    except:
        error_msg = "%s" % traceback.format_exc()
        return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)


# 活动展示
def pc_show_activity(request):
    try:
        get_page = request.GET.get("page")
        get_row = request.GET.get("row")
        get_keyword = request.GET.get('keyword')
        get_activity_result = Activity.objects.filter(status=constant.UNDERWAY)

        data = []
        if get_keyword:
            get_activity_result = Activity.objects.filter(
                Q(activitytitle__contains=get_keyword) | Q(content__contains=get_keyword) | Q(
                    city__contains=get_keyword)).filter(status=constant.UNDERWAY)
        start, stop = get_page_start_end(get_page, get_row, get_activity_result)
        data_count = len(get_activity_result)
        for count in range(start, stop):
            if count >= data_count:
                break
            row = {
                # 活动图片
                "activity_pic": "%s%s" % (constant.FILE_ADDRESS, get_activity_result[count].picture),
                # 活动编号
                "activity_no": get_activity_result[count].remark,
                # 活动名称
                "activity_name": get_activity_result[count].activitytitle,
                # 活动简介
                "content": get_activity_result[count].content,
                # 活动id
                "activity_id": get_activity_result[count].activityid,
                # 活动城市
                'activity_city': get_activity_result[count].city

            }
            data.append(row)
        return HttpResponse(json.dumps([data, data_count]), content_type=constant.CONTENT_TYPE)
    except:
        error_msg = "%s" % traceback.format_exc()
        return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)


# 查看活动详情
def pc_activity_detail(request):
    try:
        activity_id = int(request.GET.get("activityId"))
        activity_obj = Activity.objects.get(activityid=activity_id, status=constant.ACTIVITY_PROCESSING)
        activity_host_result = Activityhost.objects.filter(activityid=activity_id)
        activity_guest_result = Activityguest.objects.filter(activityid=activity_id)
        activity_sign_result = Activitysign.objects.filter(activityid=activity_id)
        if activity_obj:
            # 主持人信息
            data1 = []
            for activity_host in activity_host_result:
                dic1 = {
                    # 主持人id
                    'host_id': activity_host.hostid,
                    # 主持人图片
                    'pic': "%s%s" % (constant.FILE_ADDRESS, activity_host.picaddress),
                    # 主持人姓名
                    'name': activity_host.name,
                    # 主持人介绍
                    'introduce': activity_host.introduce
                }
                data1.append(dic1)
            # 嘉宾信息
            data2 = []
            for activity_guest in activity_guest_result:
                dic2 = {
                    # 嘉宾id
                    'guest_id': activity_guest.guestid,
                    # 嘉宾图片
                    'pic': "%s%s" % (constant.FILE_ADDRESS, activity_guest.picaddress),
                    # 嘉宾姓名
                    'name': activity_guest.name,
                    # 嘉宾介绍
                    'introduce': activity_guest.introduce
                }
                data2.append(dic2)

            # 活动报名人信息
            # data3 = []
            # for activity_sign in activity_sign_result:
            #     user_id = activity_sign.userid
            #     user = Users.objects.get(userid=user_id)
            #     dic3 = {
            #         # 报名id
            #         'sign_id': activity_sign.id,
            #         # 活动id
            #         'activity_id': activity_sign.activityid,
            #         # 用户id
            #         'user_id': user_id,
            #         # 姓名
            #         'user_name': user.username,
            #         # 手机号
            #         'user_phone': user.userphone,
            #         # 报名时间
            #         'sign_time': activity_sign.signtime.strftime("%Y.%m.%d"),
            #         # 职业
            #         'profession': activity_sign.profession,
            #         # 年龄
            #         'age': activity_sign.age,
            #         # 性别
            #         'sex': activity_sign.sex,
            #         # 爱好
            #         'hobby': activity_sign.hobby,
            #         # 区域
            #         'area': activity_sign.area,
            #         # 地址
            #         'address': activity_sign.address
            #     }
            #     data3.append(dic3)
            data = {
                # 活动id
                'activity_id': activity_obj.activityid,
                # 活动编号
                'activity_no': activity_obj.remark,
                # 活动介绍
                'activity_content': activity_obj.content,
                # 活动图片
                'activity_pic': '%s%s' % (constant.FILE_ADDRESS, activity_obj.picture),
                # 活动名称
                'activity_name': activity_obj.activitytitle,
                # 活动区域
                'activity_city': activity_obj.city,
                'activity_time': activity_obj.activitytime,
                # 主持人
                'host': data1,
                # 嘉宾
                'guest': data2,
                # 活动报名人信息
                # 'sign': data3

            }
            return HttpResponse(json.dumps(data), content_type=constant.CONTENT_TYPE)
    except Exception as exc:
        error_msg = "%s" % traceback.format_exc()
        return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)


# 活动名称
def show_activity_name(request):
    activity_list = Activity.objects.all()
    activity_names = []
    for activity_name in activity_list:
        activity_names.append(activity_name.activitytitle)

    return HttpResponse(json.dumps(activity_names), content_type=constant.CONTENT_TYPE)


# 活动报名人数
def join_activity_num(request):
    try:
        get_page = request.GET.get("page")
        get_row = request.GET.get("row")
        get_keyword = request.GET.get('keyword')
        get_activity_id = request.GET.get('activityId')
        get_join_activity_result = Activitysign.objects.filter(activityid=int(get_activity_id))

        data = []
        if get_keyword:
            get_join_activity_result = Activitysign.objects.filter(
                Q(name__contains=get_keyword) | Q(area__contains=get_keyword) | Q(
                    address__contains=get_keyword) | Q(phone__contains=get_keyword) | Q(
                    sex__contains=get_keyword)).filter(activityid=int(get_activity_id))
        data_count = len(get_join_activity_result)
        start, stop = get_page_start_end(get_page, get_row, get_join_activity_result)
        for count in range(start, stop):
            if count >= data_count:
                break

            row = {
                # 报名id
                'sign_id': get_join_activity_result[count].id,

                # 用户id
                'user_id': get_join_activity_result[count].userid,
                # 姓名
                'user_name': get_join_activity_result[count].name,
                # 手机号
                'user_phone': get_join_activity_result[count].phone,
                # 报名时间
                'sign_time': get_join_activity_result[count].signtime.strftime("%Y.%m.%d"),
                # 职业
                'profession': get_join_activity_result[count].profession,
                # 年龄
                'age': get_join_activity_result[count].age,
                # 性别
                'sex': get_join_activity_result[count].sex,
                # 爱好
                'hobby': get_join_activity_result[count].hobby,
                # 区域
                'area': ",".join(json.loads(get_join_activity_result[count].area)),
                # 地址
                'address': get_join_activity_result[count].address
            }
            data.append(row)
        return HttpResponse(json.dumps([data, data_count]), content_type=constant.CONTENT_TYPE)
    except:
        error_msg = "%s" % traceback.format_exc()
        return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)
